import axios from 'axios'
import {ElMessage} from "element-plus";

const API_BASE_URL = '/api'

// 创建axios实例
const request = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 30000 // 30秒超时
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    console.log('收到响应:', response.status, response.config.url)
    return response
  },
  (error) => {
    console.error('响应错误:', error.response?.status, error.message)
      const { message, response } = error;
      if (message.indexOf('timeout') !== -1) {
          ElMessage.error('网络超时！');
      } else if (message === 'Network Error') {
          ElMessage.error('网络连接错误！');
      }
      // 出现异常，则捕获处理（下面是交给调用处的catch)
    return Promise.reject(error)
  }
)

export default request
export { API_BASE_URL }
